<template>
  <div class="page">
    <div class="page-panel">
      <div class="page-panel-body">
        <!-- <el-button @click="handleBack" :disabled="pending">返回</el-button> -->
        <div class="pull-left">
          {{servicePrice.name}}<span v-if="servicePrice.isDelete == 1" class="service-price-delete">[{{$t('common.base.deleted')}}]</span>
        </div>
        <!-- TODO hasPermission SERVICE_EDIT -->
        <div class="pull-right">
          <el-button v-if="allowEdit && servicePrice.isDelete != 1" type="primary" @click="handleAddRemark" :disabled="pending" v-track="$track.formatParams('ADD_REMARKS')">{{$t('common.base.addRemark')}}</el-button>
          <el-button v-if="allowEdit && servicePrice.isDelete == 0" type="primary" @click="handleEdit" v-track="$track.formatParams('TO_EDIT')">{{$t('common.base.edit')}}</el-button>
        </div>
      </div>
    </div>


    <div v-if="viewLayout === 1" class="base-detail-tile-layout">
      <BaseTileLayoutTabBar
        :bar-list="layoutTabBarList"
        :now-item="leftActiveTab"
        @changeItem="tabBarChangeItem"
        @openLayoutModal="openBaseLayoutModal"
      ></BaseTileLayoutTabBar>

      <!-- left start -->
      <div v-if="leftActiveTab == 'view-detail'" class="product-template-left-layout">
        <form-view 
          :form-cell-count="formCellCount" 
          class="bbx-cell-form-view" 
          :fields="fields" 
          :value="servicePrice"
        >

          <template slot="serialNumber" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item">
              <label>{{$t('common.form.preview.serviceItem.colum2')}}</label>
              <div class="form-view-row-content">
                <span>{{ servicePrice.serialNumber }}</span>
              </div>
            </div>
          </template>

          <template slot="type" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item">
              <label>{{$t('common.form.preview.serviceItem.colum3')}}</label>
              <div class="form-view-row-content">
                <span>{{ servicePrice.type }}</span>
              </div>
            </div>
          </template>

          <template slot="unit" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item">
              <label>{{$t('common.form.preview.serviceItem.colum4')}}</label>
              <div class="form-view-row-content">
                <span>{{ servicePrice.unit }}</span>
              </div>
            </div>
          </template>

          <template slot="salePrice" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item" v-if="serviceProviderShowPrice">
              <label>{{$t('servicePrice.list.displayName.salePrice')}}</label>
              <div class="form-view-row-content">
                <span>{{ servicePrice.salePrice }}</span>
              </div>
            </div>
          </template>

          <template slot="costPrice" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item" v-if="serviceProviderShowPrice">
              <label>{{$t('servicePrice.list.displayName.deliveryPrice')}}</label>
              <div class="form-view-row-content">
                <span>{{ servicePrice.costPrice }}</span>
              </div>
            </div>
          </template>

          <template slot="productTypeList" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item" v-if="serviceProviderShowPrice">
              <label>{{$t('common.label.ralationProductType')}}</label>
              <div class="form-view-row-content">
                <span :key="item.id" v-for="item in servicePrice.productTypeList" class="product-type" @click="handleOpenGoodsMenuTab(item.id)">
                  {{ item.catalogName }}
                </span>
              </div>
            </div>
          </template>

          <template slot="logoUrl" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item" v-if="serviceProviderShowPrice">
              <label>{{$t('common.base.image')}}</label>
              <div class="form-view-row-content">
                <el-image v-if="servicePrice.logoUrl" :src="servicePrice.logoUrl" :preview-src-list="[servicePrice.logoUrl]" class="service-price-image"></el-image>
              </div>
            </div>
          </template>

          <template slot="state" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item" v-if="serviceProviderShowPrice">
              <label>{{$t('common.base.state')}}</label>
              <div class="form-view-row-content">
                {{servicePrice.state == 1? $t('common.base.enable') : $t('common.base.disable')}}
              </div>
            </div>
          </template>

          <template slot="id" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item" v-if="serviceProviderShowPrice">
              <label>{{$t('common.base.systemNo')}}</label>
              <div class="form-view-row-content">
                {{servicePrice.id}}            
              </div>
            </div>
          </template>

          <template slot="deletedBy" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item">
              <label>{{$t('servicePrice.view.deletedBy')}}</label>
              <div class="form-view-row-content">
                {{deleteRecord.operator.displayName}}            
              </div>
            </div>
          </template>

          <template slot="deleteTime" slot-scope="{value}">
            <div class="form-view-row bbx-form-cell-item">
              <label>{{$t('servicePrice.view.deleteTime')}}</label>
              <div class="form-view-row-content">
                {{deleteRecord.operateTime}}            
              </div>
            </div>
          </template>

        </form-view>
      </div>
      <!-- left end -->

      <!-- right start -->
      <div v-else-if="leftActiveTab === 'serviceLog'" class="task-timeline product-template-left-layout" ref="timeline">
        <base-timeline
          :data="recordList"
          :record-render="renderRecord"
          :loading="recordLoading"
          :loadmore="hasNextRecordPage"
          @load="loadmore"
        />
      </div>

      <div v-else-if="leftActiveTab === 'serviceRecord'" class="product-template-left-layout">
        <el-table
          :data="tableData"
          style="width:100%"
          stripe
          border
          header-row-class-name="base-table-header-v3"
          row-class-name="base-table-row-v3"
        >
          <el-table-column :label="$t('common.base.type')" sortable prop="item">
            <template slot-scope="scope">
              {{getServiceRecordTypeLabel(scope.row.item)}}
            </template>
          </el-table-column>
          <el-table-column :label="$t('common.base.quantity')" sortable prop="variation"></el-table-column>
          <el-table-column :label="$t('common.task.taskNo')" sortable prop="taskNo"></el-table-column>
          <el-table-column :label="$t('common.base.completeTime')" sortable prop="createTime">
            <template slot-scope="scope">
              {{scope.row.createTime | fmt_datetime}}
            </template>
          </el-table-column>
          <el-table-column :label="$t('common.base.operator')" sortable>
            <template slot-scope="scope">
              <template v-if="isOpenData && scope.row.executor && scope.row.executor.staffId">
                <open-data type="userName" :openid="scope.row.executor.staffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.executor.displayName || ''}}
              </template>
            </template>
          </el-table-column>
          <el-table-column :label="$t('common.form.type.customerName')" sortable prop="cusName"></el-table-column>
        </el-table>

        <el-pagination class="base-pagination"
          :background="true"
          layout="total, prev, pager, next"
          :total="serviceRecordsPage.total"
          :page-size="serviceRecordsPage.pageSize"
          :current-page="serviceRecordsPage.pageNum"
          @current-change="jump">
        </el-pagination>
      </div>

      <div v-else-if="leftActiveTab === 'regionalPricing' && isAreaPrice" class="product-template-left-layout">
        <regional-pricing-tab :serviceId="serviceId" :servicePrice="servicePrice"></regional-pricing-tab>
      </div>
      <!-- right end -->
    </div>
    <base-collapse v-if="viewLayout === 2" class="task-detail-main-content detail-main-content" :show-collapse="showCollapse" :direction.sync="collapseDirection">
      <template slot="left">
        <div class="page-panel page-main-detail" ref="detail">
          <BaseTileLayoutTabBar
            :bar-list="viewLeftBarList"
            :now-item="leftActiveTab"
            :structure="2"
            @openLayoutModal="openBaseLayoutModal"
          ></BaseTileLayoutTabBar>
          <div class="page-panel-body" v-show="collapseDirection !== 'left'">
            <el-form label-position="left" label-width="98px">
              <el-form-item :label="$t('common.form.preview.serviceItem.colum2')" prop="serialNumber">{{servicePrice.serialNumber}}</el-form-item>
              <el-form-item :label="$t('common.form.preview.serviceItem.colum3')" prop="type">{{servicePrice.type}}</el-form-item>
              <el-form-item :label="$t('common.form.preview.serviceItem.colum4')" prop="unit">{{servicePrice.unit}}</el-form-item>
              <el-form-item v-if="serviceProviderShowPrice" :label="$t('servicePrice.list.displayName.salePrice')" prop="salePrice">{{servicePrice.salePrice}} <span v-if="internationalGray"> {{ getCurrencyLabel(servicePrice.salePriceCurrency) }}</span></el-form-item>
              <el-form-item v-if="serviceProviderShowPrice" :label="$t('servicePrice.list.displayName.deliveryPrice')" prop="costPrice">{{servicePrice.costPrice}} <span v-if="internationalGray">{{ getCurrencyLabel(servicePrice.costPriceCurrency) }}</span></el-form-item>
              <el-form-item :label="$t('common.label.ralationProductType')" prop="productTypeList">
              <span :key="item.id" v-for="item in servicePrice.productTypeList" class="product-type" @click="handleOpenGoodsMenuTab(item.id)">
                {{ item.catalogName }}
              </span>
              </el-form-item>
              <el-form-item :label="$t('common.base.image')" prop="logoUrl">
                <el-image v-if="servicePrice.logoUrl" :src="servicePrice.logoUrl" :preview-src-list="[servicePrice.logoUrl]" class="service-price-image"></el-image>
              </el-form-item>
              <el-form-item :label="$t('common.base.state')" prop="state">{{servicePrice.state == 1? $t('common.base.enable') : $t('common.base.disable')}}</el-form-item>
              <el-form-item :label="$t('common.base.systemNo')" prop="id">{{servicePrice.id}}</el-form-item>
              <template v-if="servicePrice.isDelete == 1 && deleteRecord.id != null">
                <el-form-item :label="$t('servicePrice.view.deletedBy')">{{deleteRecord.operator.displayName}}</el-form-item>
                <el-form-item :label="$t('servicePrice.view.deleteTime')">{{deleteRecord.operateTime}}</el-form-item>
              </template>
            </el-form>
          </div>
        </div>
      </template>
      <template slot="right">
        <div class="page-panel page-main-addition" ref="addition" v-show="collapseDirection !== 'right'">
          <el-tabs v-model="activeTab" @tab-click="handleSwitchTab">
            <el-tab-pane :label="$t('servicePrice.view.tabLabel')" name="serviceLog">
              <div class="title"><i class="iconfont icon-gengxin"></i>{{$t('common.base.lastUpdate')}}</div>
              <div class="progress-content">
                <!-- start 时间轴 -->
                <div class="task-timeline" ref="timeline">
                  <base-timeline
                      :data="recordList"
                      :record-render="renderRecord"
                      :loading="recordLoading"
                      :loadmore="hasNextRecordPage"
                      @load="loadmore"
                  />
                </div>
                <!-- end 时间轴 -->
              </div>
            </el-tab-pane>

            <el-tab-pane :label="$t('common.base.usageRecord')" name="serviceRecord">
              <el-table
                  :data="tableData"
                  style="width:100%"
                  stripe
                  border
                  header-row-class-name="base-table-header-v3"
                  row-class-name="base-table-row-v3"
              >
                <el-table-column :label="$t('common.base.type')" sortable prop="item">
                  <template slot-scope="scope">
                    {{getServiceRecordTypeLabel(scope.row.item)}}
                  </template>
                </el-table-column>
                <el-table-column :label="$t('common.base.quantity')" sortable prop="variation"></el-table-column>
                <el-table-column :label="$t('common.task.taskNo')" sortable prop="taskNo"></el-table-column>
                <el-table-column :label="$t('common.base.completeTime')" sortable prop="createTime">
                  <template slot-scope="scope">
                    {{scope.row.createTime | fmt_datetime}}
                  </template>
                </el-table-column>
                <el-table-column :label="$t('common.base.operator')" sortable>
                  <template slot-scope="scope">
                    <template v-if="isOpenData && scope.row.executor && scope.row.executor.staffId">
                      <open-data type="userName" :openid="scope.row.executor.staffId"></open-data>
                    </template>
                    <template v-else>
                      {{scope.row.executor.displayName || ''}}
                    </template>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('common.form.type.customerName')" sortable prop="cusName"></el-table-column>
              </el-table>

              <el-pagination class="base-pagination"
                             :background="true"
                             layout="total, prev, pager, next"
                             :total="serviceRecordsPage.total"
                             :page-size="serviceRecordsPage.pageSize"
                             :current-page="serviceRecordsPage.pageNum"
                             @current-change="jump">
              </el-pagination>
            </el-tab-pane>
            <el-tab-pane :label="$t('common.base.regionalPricing')" name="regionalPricing" v-if="isAreaPrice">
              <regional-pricing-tab :serviceId="serviceId" :servicePrice="servicePrice" v-if="activeTab === 'regionalPricing'"></regional-pricing-tab>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="collapse-right" v-show="collapseDirection === 'right'">
          {{$t('servicePrice.view.tabLabel') }}
        </div>
      </template>
    </base-collapse>
    <el-dialog :title="$t('common.base.addRemark')" :visible.sync="remarkDialogVisible" width="600px">
      <service-price-remark-form ref="remarkForm" v-if="remarkDialogVisible"></service-price-remark-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="ghost" @click="remarkDialogVisible = false" >{{$t('common.base.close')}}</el-button>
        <el-button type="primary" @click="createRemark" :disabled="pending">{{$t('common.base.makeSure')}}</el-button>
      </div>
    </el-dialog> 

    <biz-layout-modal
      ref="bizLayoutModal"
      :biz-layout-type="baseLayout"
      :columns="formCellCount"
      @changeLayout="changeViewDetailLayout">
    </biz-layout-modal>
  </div>
</template> 

<script>
import { isOpenData } from '@src/util/platform';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { getRootWindow } from '@src/util/dom';
/*global AMap, moment, _init_data*/
import * as ServicePriceApi from '@src/api/ServicePriceApi';
import _ from 'lodash';
import { useFormTimezone, useStateSystemViewLayout } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()
import Page from '@src/model/Page';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import layoutMixin from '@src/mixins/layoutMixin'

import ServicePriceRemarkForm from './form/ServicePriceRemarkForm';
import RegionalPricingTab from '@src/modules/servicePrice/components/RegionalPricingTab/index.vue';
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue'

import AuthUtil from '@src/util/auth';
import { ServiceRecordTypeLabelEnum } from '@model/enum/LabelEnum'
import i18n from '@src/locales';
import { translateAction } from '@src/util/record'

import { getCurrencyDisplayName } from '@src/util/currency'
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
function createAttachmentDom(h, attachments) {
  return attachments && attachments.length > 0 ? (
    <div class="base-timeline-attachment base-file__preview">
      {attachments.map((item) => (
        <base-file-item Source={attachments} file={item} key={item.id} readonly size="small" />
      ))}
    </div>
  ) : (
    ""
  );
}

export default {
  name: 'service-price-detail-view',
  mixins: [ThemeMixin, layoutMixin],
  inject: ['initData'],
  components: {
    [ServicePriceRemarkForm.name]: ServicePriceRemarkForm,
    RegionalPricingTab,
    BaseTileLayoutTabBar,
  },
  data() {
    return {
      internationalGray,
      isOpenData,
      servicePrice: {},
      serviceRecordsPage: {
        list: [],
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      serviceRecords: [], // 原始数据
      deleteRecord: {},
      loginUser: {},

      activeTab: 'serviceLog',
      hasNextRecordPage: false,
      recordList: [], // 页面信息动态数据
      recordParams: {
        pageSize: 10,
        pageNum: 1
      },
      
      pending: false,
      recordLoading: false,
      remarkDialogVisible: false,
      auths: {},
      serviceId: '', // 服务项目id
      showCollapse: true,
      collapseDirection: '',
      viewLeftBarList: [
        {
          tabName: 'view-detail',
          disabled: true,
          tabLabel: this.$t('servicePrice.view.serviceItemInfo'),
          tabShow: true,
        }
      ],
      leftActiveTab: 'view-detail',
      formCellCount: 1
    }
  },
  computed: {
    tabs(){
      return [
        {
          tabName: 'serviceLog',
          disabled: true,
          tabLabel: this.$t('servicePrice.view.tabLabel'),
          tabShow: true,
        },
        {
          tabName: 'serviceRecord',
          disabled: true,
          tabLabel: this.$t('common.base.usageRecord'),
          tabShow: true,
        },
        {
          tabName: 'regionalPricing',
          disabled: true,
          tabLabel: this.$t('common.base.regionalPricing'),
          tabShow: true,
        },
      ]
    },
    viewLayout() {
      return this.baseLayout
    },
    layoutTabBarList() {
      return this.viewLeftBarList.concat(this.tabs);
    },
    // 处理时间后的列表数据
    tableData(){
      return disposeFormListViewTime(this.serviceRecordsPage.list, this.columns)
    },
    /* 编辑服务*/
    allowEdit() {
      return AuthUtil.hasAuth(this.auths, 'SERVICE_EDIT');
    },
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    },
    // 是否开启区域定价灰度
    isAreaPrice() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.areaPrice
    },
    fields() {
      let arr = [
        { fieldName: 'serialNumber' },
        { fieldName: 'type' },
        { fieldName: 'unit' },
        { fieldName: 'salePrice' },
        { fieldName: 'costPrice' },
        { fieldName: 'productTypeList' },
        { fieldName: 'logoUrl' },
        { fieldName: 'state' },
        { fieldName: 'id' },
      ]

      if(this.servicePrice.isDelete == 1 && this.deleteRecord.id != null) {
        const deleteArr = [
          { fieldName: 'deletedBy' },
          { fieldName: 'deleteTime' },
        ]
        arr = [...arr, ...deleteArr];
      }

      return arr;
    }
  },
  methods: {
    async initFormBuilderCellCount(){
      try {
        const { getSystemViewLayout } = useStateSystemViewLayout()
        const count = await getSystemViewLayout()
        this.baseLayout = count.baseLayout || 2;
        this.formCellCount = count.formCellCount || 1;
      }catch(e) {
        console.log(e)
      }
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    changeViewDetailLayout(type, columns) {
      this.leftActiveTab = 'view-detail' 
      this.baseLayout = type
      if(type === 2) {
        this.activeTab = 'serviceLog';
      }
      this.formCellCount = columns * 1
      this.setBaseLayoutStorage()
    },
    tabBarChangeItem(item){
      if(this.viewLayout === 1) {
        this.leftActiveTab = item.tabName;
      } else {
        this.activeTab = item.tabName;
      }
    },
    getCurrencyLabel(key) {
      key = key || 'CNY'
      return getCurrencyDisplayName(key)
    },
    // 获取服务记录类型的多语言label
    getServiceRecordTypeLabel(name) {
      return ServiceRecordTypeLabelEnum[name] || name
    },
    // 详情
    fetchServicePriceDetail(id) {
      ServicePriceApi.servicePriceDetailById({id})
        .then(res => {
          if(res.status == 0) {
            this.servicePrice = res.data
          }
        })
    },

    // 信息动态
    async fetchServicePriceLog(id) {
      const params = {
        primaryId: id || this.servicePrice.id,
        ...this.recordParams
      }
      
      return await ServicePriceApi.servicePriceLog(params)
    },

    handleEdit() {
      let currTabId = window.frameElement.dataset.id;
      // 跳转之前 修改tab标题
      this.$platform.setTabTitle({
        id: currTabId,
        title: this.$t('common.pageTitle.pageServicePriceView'),
      })
      window.location.href = `${this.$resourcePrefix}/service/price/edit/${this.servicePrice.id}`
    },

    handleBack() {
      parent.frameHistoryBack(window)
    },
    
    handleAddRemark() {
      this.remarkDialogVisible = true
    },

    handleSwitchTab({ label }) {
      this.$track.clickStat(this.$track.formatParams('DETAIL_ADD_ONS_TABS', label))
    },
    
    // 点击表格页数
    jump(currentPage){
      this.serviceRecordsPage.pageNum = currentPage;
      this.serviceRecordsPage.list = this.formatServiceRecordsTableList(currentPage);
      // this.search();
    },
    
    // 加载更多
    async loadmore() {
      try {
        this.recordParams.pageNum++;
        const moreList = await this.fetchServicePriceLog()
        this.hasNextRecordPage = moreList && moreList.length >= this.recordParams.pageSize ? true : false
        this.recordList = [...this.recordList, ...moreList]
      } catch (error) {
        console.error(`product template record loadmore err ${error}`);
      }
    },

    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, item) {
      let {
        action,
        userName,
        showInOwn,
        content,
        attachments,
        primaryName,
        staffId
      } = item;

      if (action == "备注") {
        return [
          <h5 class="main-info">
            {this.renderUserName(userName, staffId)} {this.$t('common.record.addRemark')}
            {!!showInOwn && (
              <span class="private">
                <i class="iconfont icon-account1" />
                {this.$t('common.record.onlyVisibleToYourself')}
              </span>
            )}
            。
            {this.allowDeleteRecord(item) && (
              <button
                type="button"
                class="btn-text base-timeline-delete"
                onClick={(e) => this.deleteRemark(item)}
              >
                <i class="iconfont icon-shanchu" />
                {this.$t('common.base.delete')}
              </button>
            )}
          </h5>,
          content.isDelete == "true" ? (
            <p class="text-danger">
              {this.$t('common.record.sbDeleteRemark', {name: content.deleteUserName, time: content.deleteTime})}
            </p>
          ) : (
            [
              <p class="pre-line secondary-info">{content.updateContent}</p>,
              createAttachmentDom(h, attachments),
            ]
          ),
        ];
      }

      return [
        <i18n path="common.record.servicePrice.normal" tag="h5">
          <span place="operator">{this.renderUserName(userName, staffId)} </span>
          <span place="action">{translateAction(action)}</span>
        </i18n>,
        content ? (
          content.updateFields ? (
            <p class="secondary-info">{this.$t('common.fields.modifyField.displayName')}：{content.updateFields}</p>
          ) : (
            ""
          )
        ) : (
          ""
        ),
        createAttachmentDom(h, attachments),
      ];
    },
    renderUserName(userName, staffId){
      if(isOpenData && staffId) return <strong>{<open-data type="userName" openid={staffId}></open-data>}</strong>
      return <strong>{userName}</strong>
    },
    // 是否有权限删除备注
    allowDeleteRecord(item) {
      const loginUser = parent.window.loginUser
      return (item.action == '备注' && item.content.isDelete != 'true') && (loginUser.userId == item.userId)
    },

    // 创建备注
    async createRemark() {
      const params = await this.$refs.remarkForm.pack()
      if(params === null) return;
      
      let formData = new FormData()

      formData.append("content[updateContent]", params.content.updateContent)
      formData.append("content[updateType]", params.content.updateType)
      formData.append("showInOwn", params.showInOwn)
      formData.append("primaryId", this.servicePrice.id)
      formData.append("primaryName", this.servicePrice.name)

      // formData格式传数组的问题
      if (params.attachments && params.attachments.length > 0) {
        params.attachments.forEach((item, index) => {
          for(let key in item) {
            formData.append(`attachments[${index}][${key}]`, item[key])
          }
        });
      }
      
      this.pending = true
      ServicePriceApi.servicePriceCreateRemark(formData)
        .then(res => {
          if(res.status == 0) {
            window.location.reload()
          }
        })
        .finally(() => {this.pending = false})
    },

    // 删除备注
    deleteRemark(item) {
      this.$confirm(this.$t('common.base.tip.deleteRemarkTip'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(async () => {
          const params = {
            id: item.id
          }
          ServicePriceApi.servicePriceDeleteRemark(params)
            .then(res => {
              if(res.status == 0) {
                window.location.reload()
              } else {
                this.$platform.alert(res.message);
              }
            })
        })
        .catch(() => { });
    },

    formatServiceRecordsTableList(pageNum) {
      const start = pageNum === 1 ? '0' : (pageNum -1) * 10
      const end = pageNum * 10
      return this.serviceRecords.slice(start, end)
    },
    handleOpenGoodsMenuTab(id) {
      if (!id) return;
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        fromId,
      });
    },
  },
  async mounted(){
    let initData = this.initData || {};
    this.auths = initData.authorities || {};

    const id = window.location.pathname.split('/service/price/view/')[1]
    this.serviceId = id;
    await this.initFormBuilderCellCount();

    // 获取初始化数据
    const viewInfo = await ServicePriceApi.servicePriceViewInfo({id})
    const {loginUser = {}, servicePrice = {}, serviceRecords= {}, deleteRecord} = viewInfo.data

    this.loginUser = loginUser
    this.servicePrice = servicePrice
    this.serviceRecords = serviceRecords
    this.serviceRecordsPage = {
      list: this.formatServiceRecordsTableList(1),
      total: serviceRecords.length,
      pageNum: 1,
      pageSize: 10
    }
    this.deleteRecord = deleteRecord
    
    // 获取信息动态
    this.recordList = await this.fetchServicePriceLog(id)
    this.hasNextRecordPage = this.recordList && this.recordList.length >= this.recordParams.pageSize ? true : false
  }
}
</script>
<style lang="scss" scoped>
  .page {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .detail-main-content {
    flex: 1;
  }
  ::v-deep .base-collapse {
    overflow: unset;
  }
  .collapse-right {
    height: 40px;
    line-height: 40px;
    padding-left: 12px;
    color: $text-color-regular;
    border-bottom: 2px solid $color-border-l2;
  }
.product-template-left-layout {
  padding: 20px;
  height: 84vh;
  background-color: #fff;
}
</style>

<style lang="scss">
.service-price-delete{
  float:right;
  color:#f56c6c;
}

.page-panel-body {
  display: flex;
  justify-content: space-between;
}

.pull-left {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.pull-right {
  flex-shrink: 0;
  margin-left: 16px;
}

.page-main-addition {
  overflow: hidden;
  .title {
    font-weight: 600;
  }

  .progress-content {
    padding: 15px 10px;
  }
}

.service-price-image { 
  width: 200px;
  height: 200px;
}

.icon-btn {
  vertical-align: middle;
  font-size: 18px;
  cursor: pointer;
}

.product-type {
  margin-bottom: 6px;
  cursor: pointer;
  color: $color-primary;
}

.el-form-item--small .el-form-item__content {
  line-height: 1.4;
}
.el-form-item--small .el-form-item__label {
  line-height: 1.4;
}
.detail-main-content .sample-tooltip-container .sample-tooltip-content {
  padding-left: 0;
}
.page-panel-head {
  padding-left: 16px;
}
</style>
